package com.fyy.fastdfs.utils;

import com.fyy.fastdfs.config.fdfs.FastDFSConfig;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

@Component
public class FdfsClientUtil {

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FastDFSConfig config;

    /**
     * 文件上传
     * @param file 文件对象
     * @return 文件访问地址
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 字符串文本上传
     * @param content 文本内容
     * @param fileExtension 文件后缀格式
     * @return 文件访问地址
     */
    public String uploadFile(String content,String fileExtension){
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(storePath);
    }

    /**
     * 文件删除
     * @param filePath 文件路径
     */
    public void deleteFile(String filePath){
        if(StringUtils.isEmpty(filePath)){
            return;
        }
        StorePath storePath = StorePath.parseFromUrl(filePath);
        storageClient.deleteFile(storePath.getGroup(),storePath.getPath());
    }


    /**
     * 封装完整访问路径
     * @return 访问路径
     */
    private String getResAccessUrl(StorePath storePath){
        StringBuilder filePath = new StringBuilder();
        filePath.append("http://")
                .append(config.getHost())
                .append(":")
                .append(config.getStoragePort())
                .append("/")
                .append(storePath.getFullPath());
        return filePath.toString();
    }

}
